package com.mdd.common.util.em;
import java.time.Instant;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.easemob.im.server.EMException;
import com.easemob.im.server.EMService;
import com.easemob.im.server.api.message.send.SendMessage;
import com.easemob.im.server.api.token.Token;
import com.easemob.im.server.model.EMKeyValue;
import com.easemob.im.server.model.EMUser;

/**
 * 	环信EM Utils
 * @author DEREK
 *
 */
@Component
public class EMServiceUtil {

	@Autowired
	private EMService service;

	/**
	 * 创建用户
	 * @param userName		用户ID
	 * @param pwassword		密码
	 * @return
	 */
	public EMUser createUser(String nickName) {
		try {
			EMUser user = service.user().create(nickName,nickName).block();
			// 设置用户其他属性
			//			if(null != user) {
			//				Map<String, String> map = new HashMap<>();
			//				map.put("nickname", nickName);
			//				map.put("avatar", headPic);
			//				service.metadata().setMetadataToUser(userName, map);
			//			}

			return user;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 	删除用户
	 * @param userName		用户ID
	 * @return
	 */
	public boolean deleteUser(String userName) {
		try {
			service.user().delete(userName).block();
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 	发送系统消息
	 * @param title			标题
	 * @param usernames		接受者ID
	 * @return
	 */
	public boolean sendSystemMsg(String title,Set<String> usernames) {
		try {
//			Consumer<Set<EMKeyValue>> customizer = c ->{
//				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
//				while (entries.hasNext()) {
//					Map.Entry<String,Object> entry = entries.next();
//					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
//				}
//			};
			SendMessage send = service.message().send();
			send.fromUser("XT999999").toUsers(usernames)
			.text(msg -> msg.text(title))
			//.extension(customizer)
			.send()
			.block();
			System.out.println("推送成功(无扩展字段)：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	发送系统消息
	 * @param title			标题
	 * @param usernames		接受者ID
	 * @param map
	 * @return
	 */
	public boolean sendSystemMsg(String title,Set<String> usernames,Map<String,Object> map) {
		try {
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser("XT999999").toUsers(usernames)
			.text(msg -> msg.text(title))
			.extension(customizer)
			.send()
			.block();
			System.out.println("推送成功：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	发送官网消息
	 * @param title			标题
	 * @param usernames		接受者ID
	 * @param map
	 * @return
	 */
	public boolean sendOfficialMsg(String title,Set<String> usernames,Map<String,Object> map) {
		try {
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser("GF999999").toUsers(usernames)
			.text(msg -> msg.text(title))
			.extension(customizer)
			.send()
			.block();
			System.out.println("推送成功GF999999：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	
//	public boolean sendTextMsg() {
//		 Set<String> toUsers = new HashSet<>();
//		 toUsers.add("toUserName");
//		EMTextMessage textMessage = new EMTextMessage().text("hello-我来测试发送消息");
//		Set<EMKeyValue> exts = new HashSet<>();
//		exts.add(EMKeyValue.of("key", "value"));
//		try {
//		     EMSentMessageIds messageIds = service.message().sendMsg("fromUserName", "users", toUsers, textMessage, exts).block();
//		 } catch (EMException e) {
//		     e.getErrorCode();
//		     e.getMessage();
//		 }
//		return true;
//	}

	/**
	 * 	发送自定义消息
	 * @param formUserId	发送者ID
	 * @param toUserId		接收者ID
	 * @param customEvent	主题
	 * @param map			参数<K,V>
	 * @return
	 */
	public boolean sendCustomMsg(String formUserId,String toUserId,String customEvent,Map<String,Object> map) {
		try {
//			Set<EMKeyValue> set = new HashSet<EMKeyValue>();
//			Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
//			while (entries.hasNext()) {
//				Map.Entry<String,Object> entry = entries.next();
//				set.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
//			}
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser(formUserId).toUser(toUserId)
			.custom(msg -> msg.customEvent(customEvent))
			.extension(customizer)
			.send()
			.block();
			System.out.println("消息发送成功");
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean sendNoticeOfReceipt(String toUserId,String content) {
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("content", content);
			
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser("XT999999").toUser(toUserId)
			.custom(msg -> msg.customEvent("noticeOfReceipt"))
			.extension(customizer)
			.send()
			.block();
			System.out.println("消息发送成功");
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	拉黑用户
	 * @param fromUser		被阻止的用户的用户名
	 * @param toUser		接收消息的用户的用户名
	 * @return
	 */
	public boolean blockUser(String fromUser,String toUser) {
		try {
			service.block().blockUserSendMsgToUser(toUser, fromUser).block();
			return true;
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	取消拉黑用户
	 * @param fromUser		被阻止的用户的用户名
	 * @param toUser		接收消息的用户的用户名
	 * @return
	 */
	public boolean unblockUser(String fromUser,String toUser) {
		try {
			service.block().unblockUserSendMsgToUser(toUser, fromUser).block();
			return true;
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	获取用户在线状态
	 * @param userName
	 * @return
	 */
	public boolean isOnline(String userName) {
		try {
			Boolean isOnline = service.user().isUserOnline(userName).block();
			return isOnline;
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	强制用户下线
	 * @param userName
	 * @return
	 */
	public boolean forceLogoutAllDevices(String userName) {
		try {
			service.user().forceLogoutAllDevices(userName).block();
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 	获取APP Token
	 * @return
	 */
	public String getAppToken() {
		try {
			Token block = service.token().getAppToken().block();
			return block.getValue();
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
		}
		return "";
	}
	
	/**
	 * 	获取历史消息
	 * @return
	 */
	public String getHistoryAsUri() {
		 Instant now = Instant.parse("2023-10-24T16:00:00.631Z").minusMillis((TimeUnit.HOURS.toMillis(8)));
	     String historyUrl = service.message().getHistoryAsUri(now).block();
	     return historyUrl;
	}
}
